<?php

/**
 * Classe : Enseignant
 * @author Remi
 * @author Jey
 * @version 1.0
 */
class Enseignant extends Utilisateur
{

    /**
     * @var int
     */
    protected $IdUFR;
    /**
     * @var array
     */
    protected $listCriteres;
    /**
     * @var array
     */
    protected $listNouveauxCriteres;
    /**
     * @var string
     */
    protected $Message;

    /**
     *
     * @param int $id
     */
    public function __construct($id = 0)
    {
        parent::__construct($id);

        $this->listCriteres = array();
        $this->listNouveauxCriteres = array();

        $this->setIdStatutUtilisateur(1);
        if (isset($id) && !empty($id))
        {
            $sql = SQL::getInstance()->getConnection();

            $query = "	SELECT a.*, b.IdTypeCritere, b.IdCritere
                        FROM Enseignant a
                        LEFT JOIN CritereEnseignantRS b ON b.IdEnseignant = a.IdEnseignant
                        WHERE a.IdEnseignant = :id AND b.IdTypeCritere <> 1
                     ";

            $c = $sql->prepare($query);
            $c->bindParam(":id", $id, PDO::PARAM_INT);

            if ($c->execute())
            {
                $result = $c->fetchAll(PDO::FETCH_OBJ);

                $this->IdUFR = $result[0]->IdUFR;
                $this->Message = $result[0]->MessageEnseignant;

                foreach ($result as $value)
                {
                    $this->listCriteres[$value->IdTypeCritere][$value->IdCritere] = $value->IdCritere;
                }

                $this->errormsg = "Enseignant recuperee";
                $this->requeteOk = true;

                $promoCritere = PromoCritere::getListByIdEnseignant($id);
                foreach ($promoCritere as $IdPromo => $infos)
                {
                    $this->listCriteres[1][$IdPromo] = $infos;
                }
            }
            else
            {
                $this->IdUFR = 0;
                $this->Message = "";

                $this->errormsg = "SQL Failed";
                $this->requeteOk = false;
            }
            $c->closeCursor();
        }
        else
        {
            $this->IdUFR = 0;
            $this->Message = "";
            $this->listCriteres = array();
            $this->listNouveauxCriteres = array();
        }
    }

    /**
     * Insert un Enseignant dans la base
     */
    public function insert()
    {
        $IdUtilisateur = parent::insertUtilisateur();

        if (!empty($IdUtilisateur))
        {
            $sql = SQL::getInstance()->getConnection();
            $query = "INSERT INTO Enseignant
					(
						idEnseignant,
						IdUFR,
                                                MessageEnseignant
					)
					VALUES(
						:id,
						:idU,
                                                :mess
					)";

            $sql->beginTransaction();
            try
            {
                $c = $sql->prepare($query);

                $c->bindParam(':id', $IdUtilisateur, PDO::PARAM_INT);
                $c->bindParam(':idU', $this->IdUFR, PDO::PARAM_INT);

                $c->bindParam(':mess', $this->Message, PDO::PARAM_STR);

                if ($c->execute())
                {
                    $sql->commit();
                    $c->closeCursor();
                    $this->requeteOk = true;
                    $this->errormsg = "";
                }
                else
                {
                    $this->requeteOk = false;
                    $this->errormsg = $c->errorInfo();
                    $sql->rollback();
                    $c->closeCursor();
                    $this->Id = 0;
                }
            }
            catch (PDOException $Exception)
            {
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
                $sql->rollback();
                $c->closeCursor();
                $this->Id = 0;
            }
/*
            $boolCritere = true;
            $queryAdd = "
                        INSERT INTO CritereEnseignantRS
                        (
                            IdEnseignant,
                            IdTypeCritere,
                            IdCritere
                        )
                        VALUES
                        (
                            :idE,
                            :idTC,
                            :idC
                        )
                        ";
            foreach ($this->listCriteres as $IdTypeCritere => $criteres)
            {
                if ($TypeCritere == 1)
                {
                    foreach ($criteres as $IdCritere => $nbEtudianMax)
                    {
                        /*
                          $promocritere = new PromoCritere();
                          $promocritere->setIdPromo($IdCritere);
                          $promocritere->setNbEtudiantMax($nbEtudianMax);
                          $promocritere->insert();

                          $sql->beginTransaction();
                          if ($boolCritere === true)
                          {
                          $cCritereAdd = $sql->prepare($queryAdd);

                          $cCritereAdd->bindParam(':idE', $this->Id, PDO::PARAM_INT);
                          $cCritereAdd->bindParam(':idTC', $IdTypeCritere, PDO::PARAM_INT);
                          $cCritereAdd->bindParam(':idC', $promocritere->getId(), PDO::PARAM_INT);

                          if ($cCritereAdd->execute())
                          {
                          $sql->commit();
                          $cCritereAdd->closeCursor();
                          $this->requeteOk = true;
                          $this->errormsg = "";
                          }
                          else
                          {
                          $boolCritere = false;
                          }
                          }
                          else
                          {
                          $this->requeteOk = false;
                          $this->errormsg = $c->errorInfo();
                          $sql->rollback();
                          $cCritereAdd->closeCursor();
                          }
                         *
                         
                    }
                }
                else
                {
                    foreach ($criteres as $IdCritere)
                    {
                        $sql->beginTransaction();
                        if ($boolCritere === true)
                        {
                            $cCritereAdd = $sql->prepare($queryAdd);

                            $cCritereAdd->bindParam(':idE', $this->Id, PDO::PARAM_INT);
                            $cCritereAdd->bindParam(':idTC', $IdTypeCritere, PDO::PARAM_INT);
                            $cCritereAdd->bindParam(':idC', $IdCritere, PDO::PARAM_INT);

                            if ($cCritereAdd->execute())
                            {
                                $sql->commit();
                                $cCritereAdd->closeCursor();
                                $this->requeteOk = true;
                                $this->errormsg = "";
                            }
                            else
                            {
                                $boolCritere = false;
                            }
                        }
                        else
                        {
                            $this->requeteOk = false;
                            $this->errormsg = $c->errorInfo();
                            $sql->rollback();
                            $cCritereAdd->closeCursor();
                        }
                    }
                }
            }*/
            // ------------------------------------------- SERT A RIEN ?????? -------------------------------------------
        }
        else
        {
            $this->requeteOk = false;
            $this->errormsg = $this->errormsg;
        }
    }

    /**
     * Met à jour l'enseignant dans la base
     */
    public function update()
    {
        parent::updateUtilisateur();

        if ($this->requeteOk === true)
        {
            $sql = SQL::getInstance()->getConnection();
            $query = "	UPDATE Enseignant
			SET
                        	IdUFR = :idU,
                                MessageEnseignant = :mess
			WHERE 
				idEnseignant = :id
                    ";
            $sql->beginTransaction();
            try
            {
                $c = $sql->prepare($query);

                $c->bindParam(':id', $this->Id, PDO::PARAM_INT);
                $c->bindParam(':idU', $this->IdUFR, PDO::PARAM_INT);

                $c->bindParam(':mess', $this->Message, PDO::PARAM_STR);
                
                if ($c->execute())
                {
                    $sql->commit();
                    $c->closeCursor();
                    $this->requeteOk = true;
                    $this->errormsg = "";
                }
                else
                {
                    $this->requeteOk = false;
                    $this->errormsg = $c->errorInfo();
                    $sql->rollback();
                    $c->closeCursor();
                }
            }
            catch (PDOException $Exception)
            {
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
                $sql->rollback();
                $c->closeCursor();
            }

            if (!empty($this->listNouveauxCriteres))
            {
                // Insertion des criteres
                $listCriteresAAjouter = array();
                $listCriteresASupprimer = array();

                ksort($this->listNouveauxCriteres);
                ksort($this->listCriteres);

                $differencesCriteresNouveauxCriteres = Tools::array_diff_recursive($this->listCriteres, $this->listNouveauxCriteres);
                $differencesNouveauxCriteresCriteres = Tools::array_diff_recursive($this->listNouveauxCriteres, $this->listCriteres);

                $listCriteresAAjouter = Tools::array_intersect_recursive($differencesNouveauxCriteresCriteres, $this->listNouveauxCriteres);
                $listCriteresASupprimer = Tools::array_intersect_recursive($differencesCriteresNouveauxCriteres, $this->listCriteres);

                $boolCritere = true;
                $queryAdd = "
                        INSERT INTO CritereEnseignantRS
                        (
                            IdEnseignant,
                            IdTypeCritere,
                            IdCritere
                        )
                        VALUES
                        (
                            :idE,
                            :idTC,
                            :idC
                        )
                        ";

                foreach ($listCriteresAAjouter as $IdTypeCritere => $criteres)
                {
                    if ($IdTypeCritere == 1)
                    {
                        foreach ($criteres as $IdPromo => $infos)
                        {
                            if (!empty($infos))
                            {
                                $promocritere = new PromoCritere();
                                $promocritere->setIdPromo($IdPromo);
                                $promocritere->setNbEtudiantMax($infos['NbEtudiantMax']);
                                $promocritere->insert();

                                $sql->beginTransaction();
                                if ($boolCritere === true)
                                {
                                    $cCritereAdd = $sql->prepare($queryAdd);

                                    $cCritereAdd->bindParam(':idE', $this->Id, PDO::PARAM_INT);
                                    $cCritereAdd->bindParam(':idTC', $IdTypeCritere, PDO::PARAM_INT);
                                    $cCritereAdd->bindParam(':idC', $promocritere->getId(), PDO::PARAM_INT);

                                    if ($cCritereAdd->execute())
                                    {
                                        $sql->commit();
                                        $cCritereAdd->closeCursor();
                                        $this->requeteOk = true;
                                        $this->errormsg = "";
                                    }
                                    else
                                    {
                                        $boolCritere = false;
                                    }
                                }
                                else
                                {
                                    $this->requeteOk = false;
                                    $this->errormsg = $c->errorInfo();
                                    $sql->rollback();
                                    $cCritereAdd->closeCursor();
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach ($criteres as $IdCritere)
                        {
                            $sql->beginTransaction();
                            if ($boolCritere === true)
                            {
                                $cCritereAdd = $sql->prepare($queryAdd);

                                $cCritereAdd->bindParam(':idE', $this->Id, PDO::PARAM_INT);
                                $cCritereAdd->bindParam(':idTC', $IdTypeCritere, PDO::PARAM_INT);
                                $cCritereAdd->bindParam(':idC', $IdCritere, PDO::PARAM_INT);

                                if ($cCritereAdd->execute())
                                {
                                    $sql->commit();
                                    $cCritereAdd->closeCursor();
                                    $this->requeteOk = true;
                                    $this->errormsg = "";
                                }
                                else
                                {
                                    $boolCritere = false;
                                }
                            }
                            else
                            {
                                $this->requeteOk = false;
                                $this->errormsg = $c->errorInfo();
                                $sql->rollback();
                                $cCritereAdd->closeCursor();
                            }
                        }
                    }
                }


                $queryDelete = "
                        DELETE FROM CritereEnseignantRS
                        WHERE
                            CritereEnseignantRS.IdEnseignant = :idE
                            AND
                            CritereEnseignantRS.IdTypeCritere = :idTC
                            AND
                            CritereEnseignantRS.IdCritere = :idC
                        ";

                foreach ($listCriteresASupprimer as $IdTypeCritere => $criteres)
                {
                    if ($IdTypeCritere == 1)
                    {
                        foreach ($criteres as $IdPromo => $infos)
                        {
                            if (!empty($infos))
                            {
                                $promocritere = new PromoCritere($this->listCriteres[1][$IdPromo]['IdPromoCritere']);
                                
                                $sql->beginTransaction();
                                if ($boolCritere === true)
                                {
                                    $cCritereAdd = $sql->prepare($queryDelete);

                                    $cCritereAdd->bindParam(':idE', $this->Id, PDO::PARAM_INT);
                                    $cCritereAdd->bindParam(':idTC', $IdTypeCritere, PDO::PARAM_INT);
                                    $cCritereAdd->bindParam(':idC', $promocritere->getId(), PDO::PARAM_INT);

                                    if ($cCritereAdd->execute())
                                    {
                                        $sql->commit();
                                        $cCritereAdd->closeCursor();
                                        $promocritere->delete();
                                        $this->requeteOk = true;
                                        $this->errormsg = "";
                                    }
                                    else
                                    {
                                        $boolCritere = false;
                                    }
                                }
                                else
                                {
                                    $this->requeteOk = false;
                                    $this->errormsg = $c->errorInfo();
                                    $sql->rollback();
                                    $cCritereAdd->closeCursor();
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach ($criteres as $IdCritere)
                        {
                            $sql->beginTransaction();
                            if ($boolCritere === true)
                            {
                                $cCritereDelete = $sql->prepare($queryDelete);

                                $cCritereDelete->bindParam(':idE', $this->Id, PDO::PARAM_INT);
                                $cCritereDelete->bindParam(':idTC', $IdTypeCritere, PDO::PARAM_INT);
                                $cCritereDelete->bindParam(':idC', $IdCritere, PDO::PARAM_INT);

                                if ($cCritereDelete->execute())
                                {
                                    $sql->commit();
                                    $cCritereDelete->closeCursor();
                                    $this->requeteOk = true;
                                    $this->errormsg = "";
                                }
                                else
                                {
                                    $boolCritere = false;
                                }
                            }
                            else
                            {
                                $this->requeteOk = false;
                                $this->errormsg = $cCritereDelete->errorInfo();
                                $sql->rollback();
                                $cCritereDelete->closeCursor();
                            }
                        }
                    }
                }
                /*
                echo '-------------------------------------------------';
                echo '<br/>';
                echo 'Criteres :';
                vardump($this->listCriteres);

                echo '-------------------------------------------------';
                echo '<br/>';
                echo 'Nouveaux criteres :';
                vardump($this->listNouveauxCriteres);

                echo '-------------------------------------------------';
                echo '<br/>';
                echo 'A ajouter :';
                vardump($listCriteresAAjouter);

                echo '-------------------------------------------------';
                echo '<br/>';
                echo 'A supprimer :';
                vardump($listCriteresASupprimer);

                echo '<script type="text/javascript">alert("ok?");</script>';
                 *
                 */
            }
            else
            {
                $this->requeteOk = false;
                $this->errormsg = $this->errormsg;
            }
        }
    }

    /**
     *
     * @return int
     */
    public function getIdUFR()
    {
        return $this->IdUFR;
    }

    /**
     *
     * @param int $value
     * @return mixed
     */
    public function setIdUFR($value)
    {
        $errTab = array("boolOk" => true, "errmsg" => "");
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        if (isset($value) && !empty($value))
        {
            $this->IdUFR = $value;
            $this->errormsg = "";
        }
        else
        {
            $this->IdUFR = 0;
        }
        return $errTab;
    }

    public function getMessage()
    {
        return $this->Message;
    }

    public function setMessage($value)
    {
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        $errTab = array("boolOk" => true, "errmsg" => "");

        if (isset($value) && $value != "")
        {
            $this->Message = htmlentities($value);
        }
        else
        {
            if (!isset($value))
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "Le texte ne peut etre null !";
            }
            if (isset($value) && $value == "")
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "Le texte ne peut etre vide !";
            }
            else
            {
                $errTab["boolOk"] = false;
                $errTab["errmsg"] = "Ce texte n'est pas valide !";
            }

            $this->Message = "";
        }
        return $errTab;
    }

    // ----------------------------------- TODO ---------------------------------------------
    /**
     *
     * @param int $id
     * @return boolean
     */
    static public function isFree($id, $idPromo)
    {
        if (empty($id) || empty($idPromo))
        {
            return false;
        }
        else
        {
            $sql = SQL::getInstance()->getConnection();
            //On retourne l'entree demandee
            $query = '  SELECT *
                        FROM Enseignant e
                        INNER JOIN CritereEnseignantRS ce ON e.idEnseignant = ce.IdEnseignant
                        INNER JOIN PromoCritere pc ON ce.IdCritere = pc.IdPromoCritere
                        WHERE ce.IdTypeCritere = 1 AND ce.IdEnseignant = :id AND IdPromo = :idP
                        ';
            $c = $sql->prepare($query);
            $c->bindParam(':id', $id, PDO::PARAM_INT);
            $c->bindParam(':idP', $idPromo, PDO::PARAM_INT);
            //Execution de la requête retourne false si echec
            if ($c->execute())
            {
                $result = $c->fetch(PDO::FETCH_OBJ);
                if (!empty($result))
                {
                    //vardump($result);
                    if ( intval($result->NbEtudiant) < intval($result->NbEtudiantMax) )
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }

    // ----------------------------------- FIN TODO ---------------------------------------------

    /**
     *
     * @param int $idtype
     * @param int $idcritere
     * @return bool
     */
    public function hasChooseThisCritere($idtype=0, $idcritere=0)
    {
        if (!empty($this->listCriteres[$idtype][$idcritere]))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     *
     * @param int $idtype
     * @param int $idcritere
     */
    public function addCritere($idtype=0, $idcritere=0)
    {
        //echo '<script type="text/javascript">alert("idtype='.$idtype.' , idcritere='.$idcritere.' , nbEtudiantMax='.$nbEtudiantMax.' !!");</script>';
        if (!empty($idtype) && !empty($idcritere))
        {
            //echo '<script type="text/javascript">alert("pas promo !!");</script>';
            $this->listNouveauxCriteres[$idtype][$idcritere] = $idcritere;
        }
    }

    public function getListCritere()
    {
        return $this->listCriteres;
    }

    public function addCriterePromo($idPromo=0, $nbEtudiantMax=0, $nbEtudiant=0, $idPromoCritere=0)
    {
        if (!empty($idPromo) && !empty($nbEtudiantMax))
        {
            //echo '<script type="text/javascript">alert("addCriterePromo('.$idPromo.','.$nbEtudiantMax.','.$nbEtudiant.','.$idPromoCritere.')");</script>';
            $this->listNouveauxCriteres[1][$idPromo]["NbEtudiantMax"] = $nbEtudiantMax;
            $this->listNouveauxCriteres[1][$idPromo]["NbEtudiant"] = $nbEtudiant;
            $this->listNouveauxCriteres[1][$idPromo]["IdPromoCritere"] = $idPromoCritere;
        }
    }

    /**
     * @param int $limit
     * @param int $begin
     * @param string $name
     * @param int $ufr
     * @return mixed Array of Enseignant
     * @static
     */
    static public function getList($limit=0, $begin=0, $name="", $ufr=0)
    {
        if (empty($limit))
        {
            $sql = SQL::getInstance()->getConnection();
            $query = 'SELECT Utilisateur.* FROM Utilisateur WHERE StatutUtilisateur = "1"';
            $c = $sql->query($query);
            $result = $c->fetchAll(PDO::FETCH_OBJ);
            return $result;
        }
        else
        {
            $sql = SQL::getInstance()->getConnection();
            $query = 'SELECT Utilisateur.*, Enseignant.*
                              FROM Utilisateur
                              INNER JOIN Enseignant ON Enseignant.IdEnseignant = Utilisateur.IdUtilisateur
                              WHERE StatutUtilisateur = "1"';
            if (!empty($name))
            {
                $query .= " AND ( NomUtilisateur LIKE CONCAT('%', :nom, '%')  OR PrenomUtilisateur LIKE CONCAT('%', :prenom, '%') OR EmailUtilisateur LIKE CONCAT('%', :mail, '%'))";
            }
            if (!empty($ufr))
                $query .= "AND IdUFR = :ufr";

            $query .= ' LIMIT :begin,:limit';
            $c = $sql->prepare($query);
            $c->bindParam(':begin', $begin, PDO::PARAM_INT);
            $c->bindParam(':limit', $limit, PDO::PARAM_INT);
            if (!empty($name))
            {
                $c->bindParam(':nom', $name, PDO::PARAM_STR);
                $c->bindParam(':prenom', $name, PDO::PARAM_STR);
                $c->bindParam(':mail', $name, PDO::PARAM_STR);
            }
            //var_dump($name);
            if (!empty($ufr))
                $c->bindParam(":ufr", $ufr, PDO::PARAM_INT);
            if ($c->execute())
            {
                $result = $c->fetchAll(PDO::FETCH_OBJ);
                return $result;
            }
            else
            {
                return array();
            }
        }
    }

    /**
     *
     * @return mixed Array of Tuteur
     * @static
     */
    static public function getListTuteurs()
    {
        $sql = SQL::getInstance()->getConnection();

        $query = "
                    SELECT *
                    FROM Enseignant
                    INNER JOIN UtilisateurTypeRS ON UtilisateurTypeRS.IdUtilisateur = Enseignant.IdEnseignant
                    INNER JOIN Utilisateur ON Utilisateur.IdUtilisateur = Enseignant.IdEnseignant
                    WHERE UtilisateurTypeRS.IdTypeUtilisateur = 3
                ";
        $c = $sql->query($query);
        $result = $c->fetchAll(PDO::FETCH_OBJ);

        if (!empty($result))
        {
            return $result;
        }
        else
        {
            return array();
        }
    }

    /**
     *
     * @return mixed Array of Tuteur
     * @static
     */
    static public function getListTuteursAsc()
    {
        $sql = SQL::getInstance()->getConnection();

        $query = "
                    SELECT *
                    FROM Enseignant
                    INNER JOIN UtilisateurTypeRS ON UtilisateurTypeRS.IdUtilisateur = Enseignant.IdEnseignant
                    INNER JOIN Utilisateur ON Utilisateur.IdUtilisateur = Enseignant.IdEnseignant
                    WHERE UtilisateurTypeRS.IdTypeUtilisateur = 3
                    GROUP BY Utilisateur.NomUtilisateur ASC
                ";
        $c = $sql->query($query);
        $result = $c->fetchAll(PDO::FETCH_OBJ);

        if (!empty($result))
        {
            return $result;
        }
        else
        {
            return array();
        }
    }

    /**
     *
     * @param string $name
     * @param int $ufr
     * @return int
     * @static
     */
    static public function globalCount($name="", $ufr =0)
    {
        $sql = SQL::getInstance()->getConnection();
        $query = 'SELECT COUNT(IdUtilisateur) as count
                      FROM Utilisateur
                      INNER JOIN Enseignant ON Enseignant.IdEnseignant = Utilisateur.IdUtilisateur
                      WHERE StatutUtilisateur = "1"';
        if (!empty($name))
        {
            $query .= " AND ( NomUtilisateur LIKE CONCAT('%', :nom, '%')  OR PrenomUtilisateur LIKE CONCAT('%', :prenom, '%') OR EmailUtilisateur LIKE CONCAT('%', :mail, '%'))";
        }
        if (!empty($ufr))
            $query .= "AND IdUFR = :ufr";

        $c = $sql->prepare($query);
        if (!empty($name))
        {
            $c->bindParam(':nom', $name, PDO::PARAM_STR);
            $c->bindParam(':prenom', $name, PDO::PARAM_STR);
            $c->bindParam(':mail', $name, PDO::PARAM_STR);
        }
        //var_dump($name);
        if (!empty($ufr))
            $c->bindParam(":ufr", $ufr, PDO::PARAM_INT);
        if ($c->execute())
        {
            $result = $c->fetch(PDO::FETCH_OBJ);
            return $result->count;
        }
        else
        {
            return array();
        }
    }

}

?>